import requests
from bs4 import BeautifulSoup
import pymysql
import time
import random

class T_X_recruit():
    def __init__(self):
        self.db = pymysql.connect(host='192.168.133.4', user='root', password='123456', database='self_student_jobs')
        self.cursor = self.db.cursor()

    def get_html(self, url):
        response = requests.get(url=url)
        if response.status_code == 200:
            return response.text
        raise Exception('No data~')

    def parse_data(self, html_data):
        soup = BeautifulSoup(html_data, 'html.parser')
        paragraphs = soup.find_all('h2')
        for h2 in paragraphs:
            title = h2.get_text()
            print(title)
            self.save_data(title)

    def save_data(self, title):
        sql = 'INSERT INTO people (title) VALUES (%s)'
        self.cursor.execute(sql, (title,))
        self.db.commit()

    def close_db(self):
        self.db.close()

    def main(self):
        url = "https://www.renwu.org.cn/category/baike/page/3"
        html_data = self.get_html(url)
        self.parse_data(html_data)
        self.close_db()

# 创建实例并运行主函数
t_x_recruit = T_X_recruit()
t_x_recruit.main()
